const { Transform } = require('stream');
const _ = require("lodash");
const moment = require("moment");
const utils = require('../../utils');

module.exports = function (sep, { keepEmpty, format } = {}) {
  const stream = new Transform({ objectMode: true });
  format = utils.parseFunction(format);
  if (sep && (sep.keepEmpty !== undefined || sep.format !== undefined)) {
    keepEmpty = sep.keepEmpty;
    format = sep.format;
    sep = undefined;
  }
  stream._transform = async function (chunk, encoding, callback) {
    utils.debug('splitTransform [chunk]:', chunk);
    let list;
    if (sep) {
      list = chunk.split(sep);
    } else if (/\n/.test(chunk)) {
      list = chunk.split(/\r?\n/);
    } else {
      list = chunk.split(/\s+|，|,|；|;/);
    }
    list = list.map(o=>o.trim());
    !keepEmpty && (list = list.filter(Boolean));
    list = format ? await format(list, { _, moment, utils }) : list;
    for (const obj of list) {
      stream.push(obj);
    }
    callback();
  };

  stream.on('finish', function () {
    utils.debug('splitTransform [finish]');
  });

  return stream;
};